<template>
	<view class="tableCom bg-fff">
        <view class="topBox flex bg-fff">
            <view class="titleBox">
                <view class="title font7 bottom-10 font16 fontBold txtHidden">{{product.title}}·智慧选房一房一价表</view>
                <view class="font12" v-if="averagePrice?.buildingType">{{averagePrice.buildingType}}均价<text class="font15 fontBold col-error">{{averagePrice.price}}</text>元/平</view>
                <!-- <view class="priceBox font8 top-10" v-if="solarList.length>0">注：日照时长为{{solarList[solarCurr].value}}(9-15时)在售楼栋的日照时长，<text class="iconArrow bg iconArrowUp"></text><text class="iconArrow bg iconArrowDown"></text>升降符号代表与均价比对后的差价</view>
                <view class="colors top-10 font7">
                    <view class="colorItem right-5" v-for="(colorItem, index) in colorList" :key="index">
                        {{colorItem.hours}}小时<text class="colorBg left-5" :style="{backgroundColor: colorItem.color}"></text>
                    </view>
                </view> -->
                
                <view class="tablePriceImage flex top-10 font12">
                    <view class="btnBox boxShow right-10 flex" @click="toOneHouseOnePriceImage">
                        <text class="iconBox housePriceBg bg right-10"></text>
                        一房一价图
                    </view>
                    <!-- <view class="btnBox boxShow flex" @click="toAllSunshine">
                        <text class="iconBox sunshineBg bg right-10"></text>
                        查看全部日照
                    </view> -->
                </view>
                <view class="top-8 font7 mianze">
                    以上智慧选房一房一价和日照测算等信息，仅供参考以实际交房为准。
                </view>
            </view>
        </view>
        
        <!-- <radio-group @change="chooseSolar" class="top-20 left-15" v-if="solarList.length>0">
            <label class="right-3" v-for="(radioItem, radioI) in solarList" :key="radioItem.value">
                <radio class="radios" :value="radioItem.value" :checked="radioI === solarCurr" />
                {{radioItem.value}}
            </label>
        </radio-group> -->
        
        <block v-if="unitNavs.length>0">
            <scroll-view :scroll-x="true" class="navs top-10">
                <block v-for="(nav, index) in unitNavs" :key="index">
                    <view class="navItem" :class="unitCurr === index ? 'active fontBold':''" @click="chooseUnit(index)">
                        {{nav.building}}幢{{nav.unit?nav.unit+'号':''}}
                        <text class="houseTypeTag col-fff font8" v-if="index === unitCurr && unitNavs[unitCurr].buildingType">{{unitNavs[unitCurr].buildingType}}</text>
                    </view>
                </block>
            </scroll-view>
            <view class="searchInpBox boxShow flex" @click="openYusuanModal">
                <view class="searchLeft left-5 font12 flex">
                    <u-icon name="search" color="#3E3A3A" size="15"></u-icon>
                    <text class="left-10 col-grey">{{yusuanQuJian}}</text>
                </view>
                <view class="rightIcon">
                    <u-icon name="arrow-right" color="#3E3A3A" size="14"></u-icon>
                </view>
            </view>
        </block>
        <block v-if="floorList.length>0">
            <view class="tableBox flex">
                <view class="floorBox text-center">
                    <view class="floor flex" v-for="(item,index) in floorList" :key="index">
                        <view class="floorType flex floorShiji">
                            <text class="fontBold font15">{{item.floor_123}}</text>
                            <view class="top-3">层</view>
                            <text class="font10">(实际)</text>
                        </view>
                        <view class="floorType flex floorMingyi">
                            <text class="fontBold font15">{{item.floor}}</text>
                            <view class="top-3">层</view>
                            <text class="font10">(名义)</text>
                        </view>
                    </view>
                </view>
                <scroll-view :scroll-x="true" class="tableScroll">
                    <view class="floorsBox" v-for="item in floorList" :key="item.floor">
                        <view class="roomBox" v-for="(room, roomIndex) in item.houseList" :key="roomIndex">
                            <view v-if="room.size || room.price">
                                <view class="room text-center flex" :class="room.section ? 'activeYusuan':'bg-F1F1F1'">
                                    <view class="fontBold">{{item.floor}}0{{room.room}}</view>
                                    <view class="price top-10 font12 fontBold">{{room.size}}m²</view>
                                    <view class="col-bf7c03 top-8"><text class="font10">总价</text>{{room.amount}}万</view>
                                    <view class="top-8">{{room.price}}元/m²</view>
                                    <view class="flex top-8" v-if="room.diffPrice > 0">
                                        <text class="iconArrow bg iconArrowUp right-5"></text>
                                        {{room.diffPrice}}
                                    </view>
                                    <view class="flex top-8" v-if="room.diffPrice < 0">
                                        <text class="iconArrow bg iconArrowDown right-5"></text>
                                        {{room.diffPrice}}
                                    </view>
                                    
                                    <!-- <block v-if="room.sun_min">
                                        <view class="sunBox top-5 flex col-fff" :class="{'bg-5195B7': room.sun_min <=1, 'bg-7DAA49': room.sun_min ==2, 'bg-FFCE00': room.sun_min==3, 'bg-F79800': room.sun_min==4, 'bg-FF4800': room.sun_min==5, 'bg-A80000': room.sun_min>=6}">
                                            <image class="iconSun" src="https://image.srea.org.cn/xcx/icon/icon-sun.png" mode="heightFix"></image>
                                            <view class="sunTime flex">
                                                <view class="font7">
                                                    日照
                                                </view>
                                                <text class="fontBold left-3">{{room.sun_min}}</text>
                                            </view>
                                        </view>
                                    </block> -->
                                    <view class="top-8 font12" v-if="room.comment">{{room.comment}}</view>
                                </view>
                            </view>
                            <view class="room bg-F1F1F1" v-else></view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </block>

        <up-empty text="暂无数据" mode="list" marginTop="100" v-if="floorList.length === 0"></up-empty>

        <up-modal ref="yusuanModal" :show="displayYusuan" title="价额区间(万)" :showCloseBtn="false" :closeOnClickOverlay="true" @close="displayYusuan = false" @confirm="confirmYusuan">
            <view class="yusuanModal width-100">
                <view class="font11 yusuanDesc top-10">
                    *匹配总价的房源将以飘红展示！
                </view>
                <view class="yusuanBox flex text-center">
                    <input class="inpBox" type="number" v-model="amountMin" placeholder="最小" :focus="focusMin" @confirm="confirmMin" />至
                    <input class="inpBox" type="number" v-model="amountMax" placeholder="最大" :focus="focusMax" @confirm="confirmMax" />
                </view>
            </view>
        </up-modal>
	</view>
</template>
<script setup>
import { ref, computed, watchEffect, nextTick } from 'vue';
import { useConfigStore } from '@/store/index';
import { storeToRefs } from 'pinia';

const configStore = useConfigStore();
const { puid } = storeToRefs(configStore);

// Props 定义
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({})
  },
  product: {
    type: Object,
    default: () => ({})
  }
});

// 使用 shallowRef 优化大数据集的响应性能
const tableList = ref([]);
const solarList = ref([]);
const unitNavs = ref([]);
const floorList = ref([]);

// 简单数据使用 ref
const averagePrice = ref(null);
const solarCurr = ref(0);
const unitCurr = ref(0);
const displayYusuan = ref(false);
const amountMin = ref(null);
const amountMax = ref(null);
const focusMin = ref(false);
const focusMax = ref(false);

// 使用 computed 缓存计算结果
const yusuanQuJian = computed(() => {
  if (!amountMin.value || !amountMax.value) {
    return '输入您的总价预算，查找符合条件的房源';
  }
  return `${amountMin.value}至${amountMax.value}万`;
});

// 分批处理数据以避免阻塞
const processListInBatches = async (list, prices, batchSize = 5) => {
  const result = [];
  for (let i = 0; i < list.length; i += batchSize) {
    const batch = list.slice(i, i + batchSize);
    const processedBatch = await processBatch(batch, prices);
    result.push(...processedBatch);
    // 给UI线程喘息的机会
    await new Promise(resolve => setTimeout(resolve, 0));
  }
  return result;
};

// 处理单个批次的数据
const processBatch = async (batch, prices) => {
  return batch.map(solar => {
    const processedSolar = { ...solar };
    processedSolar.list = solar.list.map(building => {
      const processedBuilding = { ...building };
      processedBuilding.unit_list = building.unit_list.map(unit => {
        return processUnitData(unit, prices);
      });
      return processedBuilding;
    });
    return processedSolar;
  });
};

// 处理单元数据
const processUnitData = (unit, prices) => {
  const processedUnit = { ...unit };
  if (!unit.floor_list?.length) return processedUnit;

  // 设置房号
  processedUnit.rooms = [];
  const maxRoom = unit.max_room;

  // 找到完整的楼层数据
  const completeFloor = unit.floor_list.find(floor => 
    floor.house_list.length === maxRoom
  );

  if (completeFloor) {
    processedUnit.rooms = completeFloor.house_list.map((house, index) => {
      const roomIndex = unit.left ? maxRoom - 1 - index : index;
      return house.room;
    });
  }

  // 处理楼层数据
  processedUnit.floor_list = unit.floor_list.map(floor => {
    return setupFloorData(floor, processedUnit.rooms, prices);
  });

  return processedUnit;
};

// 设置楼层数据
const setupFloorData = (floor, rooms, prices) => {
  const processedFloor = { ...floor };
  const maxRoomArr = rooms.map(room => ({
    amount: '',
    max_sun: 0,
    min_sun: 0,
    price: '',
    room,
    size: '',
    diffPrice: 0,
    section: false
  }));

  processedFloor.houseList = maxRoomArr.map(roomData => {
    const house = floor.house_list.find(h => h.room === roomData.room);
    if (!house) return roomData;

    const priceItem = prices.find(p => p.value === house.type);
    if (priceItem) {
      return {
        ...house,
        diffPrice: (house.price - priceItem.price).toFixed(1),
        section: false
      };
    }
    return { ...house, section: false };
  });

  return processedFloor;
};

// 使用 watchEffect 替代 watch
watchEffect(async () => {
  // 确保 detail 存在且有数据
  if (!props.detail || !Object.keys(props.detail).length) {
    resetData();
    return;
  }

  try {
    const { price = [], list = [] } = props.detail;
    if (!list.length) {
      resetData();
      return;
    }

    // 使用 nextTick 避免同步更新导致的性能问题
    await nextTick();
    
    // 分批处理数据
    const processedList = await processListInBatches(list, price);
    tableList.value = processedList;
    
    // 更新其他相关数据
    if (tableList.value.length) {
      solarList.value = tableList.value.map(item => ({ value: item.title }));
      await nextTick();
      
      if (solarList.value.length) {
        chooseSolar({ detail: solarList.value[0] });
        changeUnit();
      }
    }
  } catch (error) {
    console.error('数据处理错误:', error);
    resetData();
  }
});

// 更新相关数据
const updateRelatedData = async () => {
  if (!tableList.value.length) return;
  
  solarList.value = tableList.value.map(item => ({ value: item.title }));
  await nextTick();
  
  if (solarList.value.length) {
    chooseSolar({ detail: solarList.value[0] });
  }
};

// 常量配置
const colorList = [
  { hours: 1, color: '#5195B7' },
  { hours: 2, color: '#7DAA49' },
  { hours: 3, color: '#ffa600' },
  { hours: 4, color: '#ff6200' },
  { hours: 5, color: '#f6002d' },
  { hours: 6, color: '#A80000' }
];

const modalStyles = {
  titleStyle: {
    textAlign: 'left',
    paddingLeft: '28rpx'
  },
  confirmStyle: {
    color: '#FAA000'
  }
};

// 方法定义
function resetData () {
  tableList.value = [];
  solarList.value = [];
  solarCurr.value = 0;
  unitCurr.value = 0;
  unitNavs.value = [];
  floorList.value = [];
};

const changeSolar = () => {
  if (!tableList.value.length) return;
  
  solarList.value = tableList.value.map(item => ({ value: item.title }));
  chooseSolar({ detail: solarList.value[0] });
  changeUnit();
};

const chooseSolar = ({ detail }) => {
  solarCurr.value = solarList.value.findIndex(item => item.value === detail.value);
  changeUnit();
};

const changeUnit = () => {
  const currSolar = tableList.value[solarCurr.value];
  if (!currSolar?.list.length) return;

  unitNavs.value = currSolar.list.reduce((acc, building) => {
    building.unit_list.forEach(unit => {
        //找到单元内第一个有效的房间
        const validRoom = unit.floor_list.find(floor => floor.houseList.find(house => house.size && house.price));
        const findType = props.detail.price.find(item => item.value === validRoom.houseList[0].type);

      acc.push({
        building: building.building,
        price: findType?.price,
        unit: unit.unit,
        buildingType: findType?.label
      });
    });
    return acc;
  }, []);

  chooseUnit();
};

const chooseUnit = (index = 0) => {
  unitCurr.value = index;
  averagePrice.value = unitNavs.value[unitCurr.value];
  bindFloorHouse();
};

const bindFloorHouse = () => {
  const currUnit = tableList.value[solarCurr.value]?.list
    .find(item => item.building === unitNavs.value[unitCurr.value].building)
    ?.unit_list
    .find(item => item.unit === unitNavs.value[unitCurr.value].unit);

  floorList.value = currUnit?.floor_list || [];
};

// 预算相关方法
const searchAmountHouse = () => {
  let matchCount = 0;
  const min = Number(amountMin.value);
  const max = Number(amountMax.value);

  tableList.value[solarCurr.value].list.forEach(building => {
    building.unit_list.forEach(unit => {
      unit.floor_list.forEach(floor => {
        floor.houseList.forEach(house => {
          const amount = Number(house.amount);
          if (amount && amount >= min && amount <= max) {
            matchCount++;
            house.section = true;
          } else {
            house.section = false;
          }
        });
      });
    });
  });

  if (matchCount === 0) {
    uni.$u.toast('暂无匹配您的预算房源');
  }
};

const confirmYusuan = () => {
  if(!!amountMin.value && !!amountMax.value) {
    searchAmountHouse();
    displayYusuan.value = false
  }else {
    uni.$u.toast('请输入预算最大值和最小值');
  }
};

const openYusuanModal = () => {
  displayYusuan.value = true;
  nextTick(() => {
    focusMin.value = true;
  })
};

// 页面跳转方法
const toOneHouseOnePriceImage = () => {
  uni.navigateTo({
    url: `/pages/product/one-house-one-price/one-house-one-price-image?productId=${props.product.productId}&kaiId=${props.product.kaiId}&title=${props.product.title}&puid=${puid.value}&prepage=一房一价表-${props.product.productId}-${props.product.title}`
  });
};

const toAllSunshine = () => {
  uni.navigateTo({
    url: `/pages/product/sunshine/index?productId=${props.product.productId}&kaiId=${props.product.kaiId}&title=${props.product.title}&puid=${puid.value}&prepage=日照分析列表-${props.product.productId}-${props.product.title}`
  });
};
</script>

<style scoped lang="scss">
    .tableCom{
        min-height: 80vh;
        border-top: 1rpx solid #FFFFFF;
        .iconArrowDown{
            background-image: url("https://image.srea.org.cn/xcx/icon/icon-arrow-down-primary.png");
        }
        .iconArrowUp{
            background-image: url("https://image.srea.org.cn/xcx/icon/icon-arrow-up-error.png");
        }
        .topBox{
            justify-content: space-between;
            padding: 40rpx 22rpx 22rpx 22rpx;
            width: 100%;
            .titleBox{
                .priceBox{
                    line-height: 1.4;
                    .iconArrow{
                        display: inline-block;
                        width: 10rpx;
                        height: 18rpx;
                        vertical-align: bottom;
                    }
                }
                .colors{
                    .colorItem{
                        display: inline-block;
                        .colorBg{
                            width: 30rpx;
                            height: 16rpx;
                            display: inline-block;
                            vertical-align: sub;
                        }
                    }
                }
                .tablePriceImage{
                    justify-content: flex-start;
                    .btnBox{
                        padding: 14rpx 20rpx;
                        border-radius: 20rpx;
                        .iconBox{
                            height: 28rpx;
                            width: 28rpx;
                            display: inline-block;
                        }
                        .housePriceBg{
                            background-image: url("https://image.srea.org.cn/xcx/icon/icon-one-house-one-price-image.png");
                        }
                        .sunshineBg{
                            background-image: url("https://image.srea.org.cn/xcx/icon/icon-all-sunshine.png");
                        }
                    }
                }
                .mianze{
                    line-height: 1.3;
                }
            }
        }
    }
	.radios{
	    transform: scale(0.8);
	}
	.navs{
	    height: 80rpx;
	    white-space: nowrap;
	    .navItem{
	        height: 76rpx;
	        line-height: 90rpx;
	        display: inline-block;
	        margin-left: 20rpx;
	        opacity: 0.8;
	        position: relative;
            &:last-child{
                margin-right: 20rpx;
            }
	        .houseTypeTag{
	            line-height: 1;
	            position: absolute;
	            left: 0;
	            top: 0;
	            padding: 4rpx 15rpx;
	            background-color: rgba(0,0,0,.8);
	            border-top-left-radius: 20rpx;
	            border-top-right-radius: 20rpx;
	            border-bottom-right-radius: 20rpx;
	        }
	    }
	    .active{
	        opacity: 1;
	        &::after{
	            content: "";
	            position: absolute;
	            bottom: 0;
	            left: 0;
	            width: 100%;
	            height: 6rpx;
	            border-radius: 6rpx;
	            border-bottom: 4rpx solid $theme-color;
	        }
	    }
	}
	.searchInpBox{
	    margin: 30rpx 22rpx;
	    border-radius: 30rpx;
	    justify-content: space-between;
	    .searchLeft{
	        height: 70rpx;
	        line-height: 70rpx;
	    }
	    .rightIcon{
	        padding: 0rpx 20rpx;
	        border-left: 2rpx solid rgba(0,0,0,.2);
	    }
	}
	.tableBox{
	    margin-top: 40rpx;
	    align-items: flex-start;
	    .floorBox{
	        width: 170rpx;
	        .floor{
	            height: 340rpx;
	            .floorType{
	                flex-direction: column;
	                width: 85rpx;
	                height: 100%;
	            }
	            .floorShiji{
	                background-color: rgba(0,0,0,.1);
	            }
	            .floorMingyi{
	                background-color: $uni-bg-color-grey;
	            }
	        }
	    }
	    .tableScroll{
	        width: calc(100% - 170rpx);
	        white-space: nowrap;
	        min-height: 200rpx;
	        
	        .floorsBox{
	            text-align: left;
	            height: 340rpx;
	            .roomBox{
	                display: inline-block;
	                vertical-align: top;
	                padding: 5rpx;
	            }
	        }
	        .room{
	            width: 215rpx;
	            height: 330rpx;
	            overflow: hidden;
                flex-direction: column;
	            .iconArrow{
	                width: 20rpx;
	                height: 32rpx;
	            }
	            
	            .sunBox{
                    width: 80%;
	                border-radius: 30rpx;
	                .iconSun{
	                    height: 40rpx;
	                }
	                .sunTime{
	                    line-height: 1.4;
	                    justify-content: flex-start;
	                }
	            }
	        }
	        .activeYusuan{
	            background-color: rgba(247, 100, 100, .15);
	        }
	    }
	}
    .yusuanModal{
        .yusuanDesc{
            margin-left: 28rpx;
        }
        .yusuanBox{
            margin: 28rpx;
            justify-content: space-between;
            .inpBox{
                width: 40%;
                height: 70rpx;
                line-height: 70rpx;
            }
        }
    }
</style>
